/*
 * core.c
 *
 *  Created on: Jun 5, 2012
 *      Author: Orlando Arias
 *	   License: GPLv3
 *
 *    t45-counter
 *    Copyright (C) 2012 Orlando Arias
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <inttypes.h>

#include <avr/interrupt.h>
#include <avr/io.h>


void main(void) __attribute__((noreturn));

volatile uint16_t counter;
volatile uint8_t demux;


ISR(TIM1_COMPA_vect){		// this executes every 0.98304 seconds
	counter++;
	if(counter == 10000) counter = 0;
}

ISR(TIM0_COMPA_vect){
	PORTB &= ~(_BV(PB4) | _BV(PB3) | _BV(PB0));	// clear decoder and blank
												// 7-segment displays

	demux++;
	if(demux == 4) demux = 0;					// select digit
	PORTB |= demux * _BV(PB3);

	uint16_t dataout = counter;

	for(uint8_t i = 0; i < demux; i++)			// obtain digit
		dataout /= 10;
	dataout %= 10;

	USIDR = (uint8_t)dataout;					// send digit using the USI
	USISR = _BV(USIOIF);
	do {
		USICR = _BV(USIWM0) | _BV(USICS1) |_BV(USICLK) | _BV(USITC);
	} while bit_is_clear(USISR, USIOIF);

	PORTB |= _BV(PB0);							// show digit
}

void main(void){

	DDRB = 0xff;

	TCCR0A = _BV(WGM01);
	OCR0A = 0xf9;			// with a prescaler of 4, 500 Hz frequency
	OCR1A = 0x3c;			// with a prescaler of 16384, 1.017252Hz frequency
	TIMSK = _BV(OCIE0A) | _BV(OCIE1A);
	sei();

	TCCR0B = _BV(CS01);		// turn on timer0
	TCCR1 = _BV(CTC1)
			| _BV(CS13)
			| _BV(CS12)
			| _BV(CS11);	// turn on timer1

	while(1);
}
